package com.myframework.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.myframework.entity.User;
import com.myframework.service.UserService;

@Controller
public class UserController {
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Autowired
	UserService userServiceImpl;
	
	@RequestMapping(value = "/insertUserByUtil.do")
	@ResponseBody
	public String insertUserByUtil() {
		User user = new User(UUID.randomUUID().toString(), "测试hibernateDao", "12345", 1);
		user = userServiceImpl.saveUser(user);
		System.out.println(user.toString());
		if(user != null) {
			return user.toString();
		} else {
			return "插入用户失败！";
		}
	}
	
	@Deprecated
	@RequestMapping(value = "/insertUser.do")
	@ResponseBody
	public String insertUser(HttpServletRequest request, HttpServletResponse response) {
		User user = new User(UUID.randomUUID().toString(), "大大", "123", 1);
		user = userServiceImpl.insertUser(user);
		System.out.println(user.toString());
		if (user != null) {
			return user.toString();
		} else {
			return "错误！";
		}
	}
	
	
	@RequestMapping(value = "/testUser.do")
	public ModelAndView testAddUser(HttpServletRequest request, HttpServletResponse response) {
		Session session = sessionFactory.openSession();
		User user = new User();
		user.setId(UUID.randomUUID().toString());
//		user.setId("f83283cd-b851-4f23-ba02-a9acf0142812");
		user.setPassword("abcde");
		user.setUserName("UserAddUserUpdate");
		user.setValid(1);
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(user);
		tx.commit();
		session.close();
		System.out.println(user);
		
		ModelAndView modelAndView = new ModelAndView("/testMVC");
		modelAndView.addObject("information", "Hello," + user.getUserName() + "!");
		return modelAndView;
	}
	
}
